<?php
session_start();
include("load-settings.php");

if(!isset($_SESSION['user']))
	die("not logged in");

$user = $_SESSION['user'];
$order = mysql_real_escape_string($_POST['id']);
$timestamp = mysql_real_escape_string($_POST['timestamp']);

$result = mysql_query("SELECT * FROM user WHERE id = $user");
$row = mysql_fetch_array($result);
$username = $row['username'];
$access_level = $row['type'];

$result = mysql_query("SELECT * FROM order_record WHERE id = $order") or die(mysql_error());
$row = mysql_fetch_array($result);
$customer = $row['user'];

if($access_level == 0)
	die;

$booster_result = mysql_query("SELECT * FROM booster_order WHERE order_record = $order") or die(mysql_error());

if(mysql_num_rows($booster_result) == 0)
{
	$booster_row = array();
	$booster_row['wins'] = 0;
	$booster_row['losses'] = 0;
	$booster_row['percent'] = 0;

	$booster = "No one";
}
else
{
	$booster_row = mysql_fetch_array($booster_result);
	
	$detail_result = mysql_query("SELECT * FROM user WHERE id = ".$booster_row['booster']);
	$detail_row = mysql_fetch_array($detail_result);
	$booster = $detail_row['username'];
	$booster_id = $booster_row['booster'];
	$id = $booster_row['id'];
}

if($access_level == 1 && $user != $booster_id)
	die("unauthorized");

$result = mysql_query("SELECT * FROM user WHERE id = ".$row['user']);
$row = mysql_fetch_array($result);
$summoner = $row['summoner'];
$region = $row['region'];
$user_name = $row['username'];
$password = $row['password'];

$order_result = mysql_query("SELECT * FROM order_record WHERE id = $order");

if(mysql_num_rows($order_result) == 0)
	header("Location: home.php");

$order_row = mysql_fetch_array($order_result);

require_once("unirest/lib/Unirest.php");

$response = Unirest::get(
  "https://teemojson.p.mashape.com/player/$region/$summoner/recent_games",
  array(
    "X-Mashape-Authorization" => "l5ekV2qGSVYpEWLviXHg4A6oRHRtqNBa"
  )
);

$page = 1;

$x = ($page-1)*5;

$returnArray = array();

$decode = json_decode($response->raw_body)->data->gameStatistics->array;

while(isset($decode[$x]))
{
	$match_array = array();

	$match_array['champion'] = $decode[$x]->championId;
	$match_array['date'] = $decode[$x]->createDate;
	$match_array['timestamp'] = strtotime($decode[$x]->createDate);
	$match_array['elo'] = $decode[$x]->eloChange;
	$match_array['spell1'] = $decode[$x]->spell1;
	$match_array['spell2'] = $decode[$x]->spell2;

	foreach($decode[$x]->statistics->array as $stat)
	{
		if($stat->statType == "CHAMPIONS_KILLED")
		{
			if(!isset($stat->value) || $stat->value == "")
				$match_array['kills'] = 0;
			else
				$match_array['kills'] = $stat->value;
		}

		if($stat->statType == "ASSISTS")
		{
			if(!isset($stat->value) || $stat->value == "")
				$match_array['assists'] = 0;
			else
				$match_array['assists'] = $stat->value;
		}

		if($stat->statType == "WIN")
		{
			if(!isset($stat->value) || $stat->value == "")
				$match_array['win'] = 0;
			else
				$match_array['win'] = $stat->value;
		}

		if($stat->statType == "GOLD_EARNED")
		{
			if(!isset($stat->value) || $stat->value == "")
				$match_array['gold'] = 0;
			else
				$match_array['gold'] = $stat->value;
		}

		if($stat->statType == "MINIONS_KILLED")
		{
			if(!isset($stat->value) || $stat->value == "")
				$match_array['minions'] = 0;
			else
				$match_array['minions'] = $stat->value;
		}

		if($stat->statType == "NUM_DEATHS")
		{
			if(!isset($stat->value) || $stat->value == "")
				$match_array['deaths'] = 0;
			else
				$match_array['deaths'] = $stat->value;
		}

		if($stat->statType == "ITEM0")
		{
			$match_array['item0'] = $stat->value;
		}
		if($stat->statType == "ITEM1")
		{
			$match_array['item1'] = $stat->value;
		}
		if($stat->statType == "ITEM2")
		{
			$match_array['item2'] = $stat->value;
		}
		if($stat->statType == "ITEM3")
		{
			$match_array['item3'] = $stat->value;
		}
		if($stat->statType == "ITEM4")
		{
			$match_array['item4'] = $stat->value;
		}
		if($stat->statType == "ITEM5")
		{
			$match_array['item5'] = $stat->value;
		}

		if(!isset($match_array['deaths']))
		{
			$match_array['deaths'] = 0;
		}
		if(!isset($match_array['kills']))
		{
			$match_array['kills'] = 0;
		}
		if(!isset($match_array['assists']))
		{
			$match_array['assists'] = 0;
		}
		if(!isset($match_array['minions']))
		{
			$match_array['minions'] = 0;
		}
		if(!isset($match_array['gold']))
		{
			$match_array['gold'] = 0;
		}
	}
	array_push($returnArray, $match_array);
	$x++;
}
$pages = ceil($x/5);

usort($returnArray, function($a, $b) {
    return $b['timestamp'] - $a['timestamp'];
});

//print_r($returnArray); die;

$response = Unirest::get(
  "https://teemojson.p.mashape.com/player/$region/$summoner/leagues",
  array(
    "X-Mashape-Authorization" => "l5ekV2qGSVYpEWLviXHg4A6oRHRtqNBa"
  )
);

$decode = json_decode($response->raw_body);

$x = 0;

$tier = "UNRANKED";
$rank = "";

while(isset($decode->data->summonerLeagues->array[$x]))
{
	if($decode->data->summonerLeagues->array[$x]->queue == "RANKED_SOLO_5x5")
	{
		$tier = $decode->data->summonerLeagues->array[$x]->tier;
		$rank = $decode->data->summonerLeagues->array[$x]->requestorsRank;
	}
	$x++;
}

$x = 0;
$champ_array = array();

while(isset($returnArray[$x]))
{
	$champ_array[$x] = $returnArray[$x]['champion'];
	$x++;
}

$champs = array_count_values($champ_array);

arsort($champs);
$champ_keys = array_keys($champs);

$x = 0;

$win_loss = array();

while(isset($champ_keys[$x]) && $x < 3)
{
	$y = 0;
	$win_loss[$x] = array();
	$win_loss[$x]['win'] = 0;
	$win_loss[$x]['loss'] = 0;
	while(isset($returnArray[$y]))
	{
		if($returnArray[$y]['champion'] == $champ_keys[$x])
		{
			if($returnArray[$y]['win'] == 1)
				$win_loss[$x]['win']++;
			else
				$win_loss[$x]['loss']++;
		}
		$y++;
	}
	$x++;
}

$champ_lookup = array();

$response = Unirest::get(
  "https://teemojson.p.mashape.com/datadragon/champion",
  array(
    "X-Mashape-Authorization" => "l5ekV2qGSVYpEWLviXHg4A6oRHRtqNBa"
  )
);

$decode = json_decode($response->raw_body)->data;
$x = 0;

foreach ($decode as $item)
{
	$champ_lookup[$x] = array();
	$champ_lookup[$x]['id'] = $item->key;
	$champ_lookup[$x]['name'] = $item->id;
	$x++;
}
//var_dump($champ_lookup); die;

//var_dump($champ_lookup[key_to_name($champ_lookup, (string)$returnArray[0]['champion'])]['name']); die;
if($returnArray[0]['timestamp'] > $timestamp)
{
	if($returnArray[0]['win'] == 1)
	{
		$result = mysql_query("SELECT * FROM booster_order WHERE id = $order") or die(mysql_error());

		$row = mysql_fetch_array($result);

		$wins = $row['wins'];
		$wins++;

		mysql_query("UPDATE booster_order SET wins = $wins WHERE id = $order");

		$order_result = mysql_query("SELECT * FROM order_record WHERE id = ".$row['order_record']);
		$order_row = mysql_fetch_array($order_result);

		if($wins - $row['losses'] == $order_row['number_of_wins'])
		{
			mysql_query("UPDATE order_record SET complete = 1 WHERE id = ".$order_row['id']);
			mysql_query("UPTADE booster_order SET status = 3 WHERE id = $order");
		}

		echo "win";
	}
	else
	{
		$result = mysql_query("SELECT * FROM booster_order WHERE id = $order") or die(mysql_error());

		$row = mysql_fetch_array($result);

		$losses = $row['losses'];
		$losses++;

		mysql_query("UPDATE booster_order SET losses = $losses WHERE id = $order");

		echo "loss";
	}
}
else
{
	echo "no change";
}

function key_to_name($products, $needle)
{
   foreach($products as $key => $product)
   {
      if ( $product['id'] === $needle )
         return $key;
   }
   return false;
}
//var_dump($decode->data->summonerLeagues->array[0]); die;
function numberToRoman($num) 
 {
     // Make sure that we only use the integer portion of the value
     $n = intval($num);
     $result = '';
 
     // Declare a lookup array that we will use to traverse the number:
     $lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
     'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
     'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
 
     foreach ($lookup as $roman => $value) 
     {
         // Determine the number of matches
         $matches = intval($n / $value);
 
         // Store that many characters
         $result .= str_repeat($roman, $matches);
 
         // Substract that from the number
         $n = $n % $value;
     }
 
     // The Roman numeral should be built, return it
     return $result;
 }

 function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}
?>